<%--
  Created by IntelliJ IDEA.
  User: Gongcj
  Date: 06-28-2019
  Time: 20:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Chat</title>
</head>
<body>
    <input type="text" id="msg">
    <button onclick="sendMsg()">发送</button><br>
    <span>聊天室内容</span>
    <div id="content"></div><br>
    <span>聊天室在线列表</span><br>
    <div id="online"></div>


</body>
<script>
    var ws;
    window.onload = function () {
        if ("WebSocket" in window){
            alert("你的浏览器支持WebSocket")
            var username = '${username}';
            ws = new WebSocket("ws://127.0.0.1:8080/chat?username="+username);

            ws.onmessage = function(evt){
                var result = JSON.parse(evt.data)
                if(result.type == 0){
                    contentInfo(result.content,result.type);
                    onlineName(result.usernames);
                }else if (result.type == 1) {

                }else {
                    contentInfo(result.from+":"+result.content,result.type);
                }

            }
        }else {
            alert("你的浏览器不支持WebSocket")
        }
    }

    function onlineName(names){
        clearOnlineInfo();
        onlineInfo("当前在线人数："+names.length,0);
        for(var index in names){
            onlineInfo(names[index]);
        }
    }

    function clearOnlineInfo() {
        document.getElementById("online").innerHTML ="";
    }

    function onlineInfo(msg,type){
        if(type == 0){
            document.getElementById("online").innerHTML += msg +"<br>";
        }else{
            document.getElementById("online").innerHTML += "<input type='checkbox' name='toNames' value='"+msg+"'>"+msg +"<br>";
        }

    }

    function contentInfo(msg,type){

        if (type == 0){
            document.getElementById("content").innerHTML += "<font color='red'>"+msg+"</font>" +"<br>";
        } else {
            document.getElementById("content").innerHTML += "<font color='green'>"+msg+"</font>" +"<br>";
        }

    }

    function sendMsg(){
        var msg = document.getElementById("msg").value;
        var to = getCheckvalue();
        var type = (to.length==0||to == null)?1:2;//1是广播，2是单聊
        var obj ={
            to:to,
            msg:msg,
            type:type //1是广播，2是单聊
        };
        ws.send(JSON.stringify(obj));
        var msg = document.getElementById("msg").value="";
    }

    function getCheckvalue(){
        obj = document.getElementsByName("toNames");
        check_val = [];
        for(k in obj){
            if(obj[k].checked)
                check_val.push(obj[k].value);
        }
        return check_val;
    }
</script>
</html>
